/*
插件下载:
   npm i axios@0.26.1 axios-miniprogram-adapter
   构建
*/

import axios from 'axios'
import adapter from 'axios-miniprogram-adapter'
axios.defaults.adapter = adapter

const baseURL = 'https://live-api.itheima.net'
const instance = axios.create({
  baseURL: baseURL
})

instance.interceptors.request.use((config) => {
  const token = getApp().token
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, (error) => {
  return Promise.reject(error)
})
instance.interceptors.response.use((res) => {
  // 2开头
  if (res.data.code === 10000) {
    return res.data
  } else {
    // 提示
    wx.utils.toast(res.data.message)
    return Promise.reject(new Error(res.data.message))
  }


}, async (error) => {
  // 非2开头
  console.dir(error)
  if (error.response && error.response.status === 401) {
    // 先抢救token(用refreshToken产生一个新的token)
    try {
      const res = await axios({
        url: baseURL + '/refreshToken',
        method: 'post',
        headers: {
          Authorization: getApp().refreshToken
        }
      })
      console.log('抢救token', res);
      //     成功（真的产生了新的token）：存储新的token,继续上一次401的请求（用新的token请求）
      getApp().setToken(res.data.data.token, res.data.data.refreshToken)
      return await wx.http(error.config)
    } catch {
      //     失败（无救）:删除token,refreshTOken,提示，跳转到登录页
      getApp().removeToken()
      wx.utils.toast(error.response.data.message)
      const pages = getCurrentPages()
      const route = '/' + pages[pages.length - 1].route
      wx.redirectTo({
        url: '/pages/login/index?back=' + route,
      })

    }

  }
  return Promise.reject(error)
})
wx.http = instance
wx.baseURL = baseURL
export default instance
export {
  baseURL
}